package com.windsea.relationshipmining.activity;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

import com.windsea.relationshipmining.R;
import com.windsea.relationshipmining.database.DBServiceHandler;
import com.windsea.relationshipmining.database.DBUserData;
import com.windsea.relationshipmining.services.WatcherService;

public class MainActivity extends Activity implements OnClickListener {

	private static final String TAG = MainActivity.class.getSimpleName();
	public String LifeTime;
	public String StartOnce;

	// / All Intents ///
	Intent callHistory, cService, smsHistory, watcherService;

	// LifeTime-Management Variables //
	public DBServiceHandler sHandler;
	public Time n;
	public long now, applifetime, terminationdate, end;
	private Cursor sO, LT;

	/* Declare all our databases */
	public DBUserData dbUserData;
	Cursor curInfo = null;
	String name, email, age;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		dbUserData = new DBUserData(getApplicationContext());
		dbUserData.open();
		curInfo = dbUserData.getInfo();

		sHandler = new DBServiceHandler(getApplicationContext());
		sHandler.open();
		sO = sHandler.getStartOnce();

		if (!sO.moveToFirst()) {
			Log.d(TAG, "--------- FirstTimeRun ----------");

			WelcomeNoteDialog hi = new WelcomeNoteDialog(MainActivity.this);
			hi.show();

			applifetime = 1000 * 60 * 60 * 24 * 15; // 15d
			n = new Time();
			n.setToNow();
			now = n.toMillis(false);
			terminationdate = now + applifetime;
			Log.d(TAG, "Now: " + now);
			Log.d(TAG, "Terminationdate: " + terminationdate);

			sHandler.insertLifeTime(terminationdate + "");
			startService();
			startWatcherService();
			// //////////
			Log.d(TAG, "Starting Services at First-Run");
			sHandler.insertStartOnce("Services have already started once");

		} else {

			Log.d(TAG, "--------- NOT FirstTimeRun ----------");
			n = new Time();
			n.setToNow();
			now = n.toMillis(false);

			LT = sHandler.getLifeTime();
			LT.moveToFirst();
			end = Long.parseLong(LT.getString(LT.getColumnIndex("LifeTime")));
			Log.d(TAG, "Now: " + now);
			Log.d(TAG, "Terminationdate: " + end);
			if (now > end) {
				Log.d(TAG, "Test-End --> Uninstall App");

				ThankyouNoteDialog thx = new ThankyouNoteDialog(
						MainActivity.this);
				thx.show();
			}
		}
		// // End of StartOnce-Check-Loop
		sHandler.close();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menumainactivity, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// default case
		super.onOptionsItemSelected(item);
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.addUserInfo:
			finish();
			Intent intent = new Intent(getApplicationContext(),
					UserInfoActivity.class);
			Bundle bundle = new Bundle();
			if (curInfo != null && curInfo.moveToFirst()) {
				bundle.putString("Info", "edit");
				intent.putExtra("UserInfo", bundle);

			} else {
				bundle.putString("Info", "insert");
				intent.putExtra("UserInfo", bundle);
			}
			curInfo.close();
			dbUserData.close();
			startActivity(intent);
			return true;
		case R.id.mainHelp:
			finish();
			Intent intentHelp = new Intent(getApplicationContext(),
					HelpActivity.class);
			startActivity(intentHelp);
			return true;
		case R.id.about:
			final AboutNoteDialog info = new AboutNoteDialog(MainActivity.this);
			info.show();
			final Timer t = new Timer();
			t.schedule(new TimerTask() {

				public void run() {
					info.dismiss();
					t.cancel();
				}
			}, 5000);
			return true;
		case R.id.policyMenu:
			final SecurityPolicyDialog policy = new SecurityPolicyDialog(
					MainActivity.this);
			policy.show();
			final Timer t2 = new Timer();
			t2.schedule(new TimerTask() {

				public void run() {
					policy.dismiss();
					t2.cancel();
				}
			}, 7000);
			return true;
		case R.id.relationChoose:
			finish();
			Intent intent2 = new Intent(getApplicationContext(),
					RelationChooserActivity.class);
			startActivity(intent2);

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (curInfo != null && curInfo.moveToFirst()) {
			menu.getItem(0).setTitle("Sửa thông tin cá nhân");
		}
		if (isServiceRunning("com.windsea.relationshipmining.services.ContactsService")
				|| isServiceRunning("com.windsea.relationshipmining.services.LogCallHistory")
				|| isServiceRunning("com.windsea.relationshipmining.services.LogSMSHistory")) {
			menu.getItem(4).setTitle("Đang xử lý...");
			menu.getItem(4).setEnabled(false);
		}
		DBServiceHandler dbHandle = new DBServiceHandler(
				getApplicationContext());
		dbHandle.open();
		Cursor cur1 = null;
		cur1 = dbHandle.getRelationDone();
		if (cur1 != null && cur1.moveToFirst()) {
			menu.getItem(4).setEnabled(false);
		}
		cur1.close();
		dbHandle.close();
		return true;
	}

	@Override
	public void onClick(View v) {

	}

	public void startService() {
		cService = new Intent();
		cService.setAction("com.windsea.relationshipmining.services.ContactsService");
		startService(cService);

	}

	public void startWatcherService() {
		// Start watcher service
		watcherService = new Intent(this.getApplicationContext(),
				WatcherService.class);
		startService(watcherService);
	}

	private boolean isServiceRunning(String serviceName) {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (serviceName.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}
}